//
//  FFTransferDetailVC.m
//  LiMaoTransfer
//
//  Created by tt on 2020/9/18.
//

#import "FFTransferDetailVC.h"
#import <LLWallet/LLWallet.h>
#import "FFPayPwdUpdateVC.h"

#define statusWait 1 // 待领取
#define statusSuccess 2 // 已领取
#define statusExpire 3 // 已过期
@interface FFTransferDetailVC ()

@property(nonatomic,strong) UIImageView *statusIconImgView;

@property(nonatomic,strong) UILabel *statusLbl; // 转账状态

@property(nonatomic,strong) UILabel *amountLbl; // 转账金额
@property(nonatomic,strong) UILabel *transferTimeLbl; // 转账时间
@property(nonatomic,strong) UILabel *receiveTimeLbl; // 收款账时间

@property(nonatomic,strong) UIButton *sureBtn; // 确认收款按钮

@property(nonatomic,strong) UILabel *tipLbl; // 提醒

@property(nonatomic,strong) UIButton *toWalletBtn; // 跳到钱包的btn

@end

@implementation FFTransferDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationBar setBackgroundColor:[UIColor clearColor]];
    
    [self.view addSubview:self.statusIconImgView];
    [self.view addSubview:self.statusLbl];
    [self.view addSubview:self.amountLbl];
    [self.view addSubview:self.sureBtn];
    [self.view addSubview:self.transferTimeLbl];
    [self.view addSubview:self.receiveTimeLbl];
    [self.view addSubview:self.tipLbl];
    [self.view addSubview:self.toWalletBtn];
    
    FFTransferResp *emptyResp = [FFTransferResp new];
    [self refresh:emptyResp];
    
    [self requestTransferDetail];
}

- (void)viewConfigChange:(WKViewConfigChangeType)type {
    if([WKApp shared].config.style == WKSystemStyleDark) {
        [self.view setBackgroundColor:[WKApp shared].config.backgroundColor];
    }else{
        [self.view setBackgroundColor:[UIColor whiteColor]];
    }
    
}

- (UIImageView *)statusIconImgView {
    if(!_statusIconImgView) {
        CGFloat size = 64.0f;
        _statusIconImgView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.lim_width/2.0f - size/2.0f,self.navigationBar.lim_bottom + 40.0f, size, size)];
    }
    return _statusIconImgView;
}

- (UILabel *)statusLbl {
    if(!_statusLbl) {
        _statusLbl = [[UILabel alloc] init];
    }
    return _statusLbl;
}

- (UILabel *)amountLbl {
    if(!_amountLbl) {
        _amountLbl = [[UILabel alloc] init];
        _amountLbl.font = [[WKApp shared].config appFontOfSizeSemibold:40.0f];
    }
    return _amountLbl;
}

- (UIButton *)sureBtn {
    if(!_sureBtn) {
        _sureBtn = [[UIButton alloc] init];
        _sureBtn.backgroundColor = [WKApp shared].config.themeColor;
        _sureBtn.lim_height = 40.0f;
        _sureBtn.lim_width = 200.0f;
        [_sureBtn setTitle:LLang(@"确认收款") forState:UIControlStateNormal];
        [_sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _sureBtn.lim_left = self.view.lim_width/2.0f - _sureBtn.lim_width/2.0f;
        _sureBtn.hidden = YES;
        _sureBtn.layer.masksToBounds = YES;
        _sureBtn.layer.cornerRadius = 4.0f;
        [_sureBtn addTarget:self action:@selector(transferSure) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}
// 转账确认
-(void) transferSure {
    [self.view showHUD];
    __weak typeof(self) weakSelf = self;
    [[WKAPIClient sharedClient] GET:@"impay/wallet/my" parameters:nil].then(^(NSDictionary* dict){
        BOOL passwordIsSet = [dict[@"password_is_set"] boolValue];
        if (!passwordIsSet){
            [WKAlertUtil alert:LLang(@"你还未设置支付密码，是否立刻设置") buttonsStatement:@[LLang(@"否"),LLang(@"是")] chooseBlock:^(NSInteger buttonIdx) {
                if(buttonIdx == 1) {
                    [[WKNavigationManager shared] pushViewController:[FFPayPwdUpdateVC new] animated:YES];
                }
            }];
        }else{
            [[WKAPIClient sharedClient] POST:[NSString stringWithFormat:@"transfers/%@/receive",self.recordNo] parameters:nil].then(^{
                [weakSelf requestTransferDetail].then(^{
                    [weakSelf.view hideHud];
                });
            }).catch(^(NSError *error){
                [self.view switchHUDError:error.domain];
            });
        }
    }).catch(^(NSError *error){
       
    });
    
}

- (UILabel *)tipLbl {
    if(!_tipLbl) {
        _tipLbl = [[UILabel alloc] init];
        _tipLbl.font = [[WKApp shared].config appFontOfSize:15.0f];
        _tipLbl.textColor = [WKApp shared].config.tipColor;
    }
    return _tipLbl;
}

- (UIButton *)toWalletBtn {
    if(!_toWalletBtn) {
        _toWalletBtn = [[UIButton alloc] init];
        [_toWalletBtn setTitle:LLang(@"查看零钱") forState:UIControlStateNormal];
        [_toWalletBtn setTitleColor:[UIColor colorWithRed:94.0f/255.0f green:110.0f/255.0f blue:148.0/255.0f alpha:1.0f] forState:UIControlStateNormal];
        [_toWalletBtn addTarget:self action:@selector(toWallet) forControlEvents:UIControlEventTouchUpInside];
        _toWalletBtn.titleLabel.font = [[WKApp shared].config appFontOfSize:15.0f];
        [_toWalletBtn sizeToFit];
        
    }
    return _toWalletBtn;
}

-(void) toWallet {
    [[WKNavigationManager shared] pushViewController:[FFWalletVC new] animated:YES];
}

- (UILabel *)transferTimeLbl {
    if(!_transferTimeLbl) {
        _transferTimeLbl = [[UILabel alloc] init];
        _transferTimeLbl.font = [[WKApp shared].config appFontOfSize:14.0f];
        _transferTimeLbl.textColor = [WKApp shared].config.tipColor;
    }
    return _transferTimeLbl;
}

- (UILabel *)receiveTimeLbl {
    if(!_receiveTimeLbl) {
        _receiveTimeLbl = [[UILabel alloc] init];
        _receiveTimeLbl.font = [[WKApp shared].config appFontOfSize:14.0f];
        _receiveTimeLbl.textColor = [WKApp shared].config.tipColor;
    }
    return _receiveTimeLbl;
}

-(AnyPromise*) requestTransferDetail {
    __weak typeof(self) weakSelf = self;
    return [[WKAPIClient sharedClient] GET:[NSString stringWithFormat:@"transfers/%@",self.recordNo] parameters:nil model:FFTransferResp.class].then(^(FFTransferResp *resp){
        [weakSelf refresh:resp];
        if(weakSelf.onStatus) {
            weakSelf.onStatus(resp.status);
        }
    }).catch(^(NSError *error){
        [[WKNavigationManager shared].topViewController.view switchHUDError:error.domain];
    });
}

-(void) refresh:(FFTransferResp*)resp {
    self.sureBtn.hidden = YES;
    self.toWalletBtn.hidden = YES;
    self.toWalletBtn.hidden = YES;
    self.tipLbl.text = @"";
    
    // 转账时间
    self.transferTimeLbl.text = [NSString stringWithFormat:LLang(@"转账时间：%@"),resp.createdAt];
    [self.transferTimeLbl sizeToFit];
    CGFloat bottomSafe = 0.0f;
    if (@available(iOS 11.0, *)) {
        bottomSafe = [[UIApplication sharedApplication].keyWindow safeAreaInsets].bottom;
    }
    self.transferTimeLbl.lim_top = self.view.lim_height - bottomSafe - 40.0f;
    self.transferTimeLbl.lim_left = self.view.lim_width/2.0f - self.transferTimeLbl.lim_width/2.0f;
    
    if(resp.status == statusWait) {
        [self.statusIconImgView setImage:[self imageName:@"transfer_wait"]];
        WKChannelInfo*channelInfo = [[WKSDK shared].channelManager getChannelInfo:[[WKChannel alloc] initWith:resp.toUID channelType:WK_PERSON]];
        if(channelInfo) {
            self.statusLbl.text = [NSString stringWithFormat:LLang(@"待%@确认收款"),channelInfo.displayName];
        }else{
            self.statusLbl.text = LLang(@"待确认收款");
        }
        
        if([[WKApp shared].loginInfo.uid isEqualToString:resp.toUID]) {
            self.sureBtn.hidden = NO;
            self.tipLbl.text = LLang(@"1天内未确认，将退还给对方");
        }else {
            self.tipLbl.text = LLang(@"1天内朋友未确认，将退还给你");
        }
        
    }else if(resp.status == statusSuccess) {
        self.toWalletBtn.hidden = NO;
        
        [self.statusIconImgView setImage:[self imageName:@"transfer_success"]];
        self.statusLbl.text = [NSString stringWithFormat:LLang(@"%@已收款"),resp.toName];
        
        self.transferTimeLbl.lim_top =  self.transferTimeLbl.lim_top - 40.0f;
        
        self.receiveTimeLbl.text = [NSString stringWithFormat:LLang(@"收款时间：%@"),resp.receiveAt];
        [self.receiveTimeLbl sizeToFit];
        self.receiveTimeLbl.lim_top = self.transferTimeLbl.lim_bottom + 5.0f;
        self.receiveTimeLbl.lim_left = self.transferTimeLbl.lim_left;
        
    }else if(resp.status == statusExpire) {
        [self.statusIconImgView setImage:[self imageName:@"transfer_expire"]];
        self.statusLbl.text = LLang(@"已退还（过期）");
    }
    // 状态
    [self.statusLbl sizeToFit];
    self.statusLbl.lim_left = self.view.lim_width/2.0f - self.statusLbl.lim_width/2.0f;
    self.statusLbl.lim_top = self.statusIconImgView.lim_bottom + 20.0f;
    
    // 金额
    self.amountLbl.text = [NSString stringWithFormat:@"¥%@",[WKMoneyUtil penny2YuanFormat:@(resp.amount)]];
    [self.amountLbl sizeToFit];
    self.amountLbl.lim_left = self.view.lim_width/2.0f - self.amountLbl.lim_width/2.0f;
    self.amountLbl.lim_top = self.statusLbl.lim_bottom + 20.0f;
    
    // 查看零钱
    self.toWalletBtn.lim_top = self.amountLbl.lim_bottom + 20.0f;
    self.toWalletBtn.lim_left = self.view.lim_width/2.0f - self.toWalletBtn.lim_width/2.0f;
    
    // 确认按钮
    self.sureBtn.lim_top = self.transferTimeLbl.lim_top - self.sureBtn.lim_height - 80.0f;
    
    // 提醒
    [self.tipLbl sizeToFit];
    self.tipLbl.lim_left = self.view.lim_width/2.0f - self.tipLbl.lim_width/2.0f;
    if([[WKApp shared].loginInfo.uid isEqualToString:resp.toUID]) { // 收款方
        self.tipLbl.lim_top = self.sureBtn.lim_bottom + 20.0f;
    }else {
        self.tipLbl.lim_top = self.amountLbl.lim_bottom + 20.0f;
    }
}

-(UIImage*) imageName:(NSString*)name {
    return [[WKApp shared] loadImage:name moduleID:@"LiMaoTransfer"];
}

@end

@implementation FFTransferResp

+ (WKModel *)fromMap:(NSDictionary *)dictory type:(ModelMapType)type {
    FFTransferResp *resp = [FFTransferResp new];
    resp.no = dictory[@"no"];
    resp.amount = [dictory[@"amount"] integerValue];
    resp.toUID = dictory[@"to_uid"];
    resp.toName = dictory[@"to_name"];
    resp.status = [dictory[@"status"] integerValue];
    resp.createdAt = dictory[@"created_at"];
    resp.receiveAt = dictory[@"receive_at"];
    resp.refundAt = dictory[@"refund_at"];
    return resp;
}


@end
